package com.ljfiction.book.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.ljfiction.book.Baner.AuthormessageBean;
import com.ljfiction.book.Baner.BookIDBean;
import com.ljfiction.book.Baner.FistHom;
import com.ljfiction.book.Baner.VersonBean;
import com.ljfiction.book.Dialog.NewVersionDialog;
import com.ljfiction.book.Dialog.NoAuthorDialog;
import com.ljfiction.book.Dialog.OkDialog;
import com.ljfiction.book.Dialog.PhoneBangding;
import com.ljfiction.book.MyView.HomwriterWindow;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.fragment.BookshelfFragment;
import com.ljfiction.book.fragment.HomeFragment;
import com.ljfiction.book.fragment.MessageFragment;
import com.ljfiction.book.fragment.MineFragment;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.myinterface.Mainlistener;
import com.ljfiction.book.tools.DownLoadService;
import com.ljfiction.book.tools.PermissionUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends BaseActivity {
    @BindView(R.id.message_numtext)
    TextView messageNumtext;
    @BindView(R.id.message_numcard)
    CardView messageNumcard;
    private MainActivity context;
    /**
     * 用于对Fragment进行管理
     * 1
     */
    public FragmentManager fragmentManager;


    public HomeFragment homeFragment;
    public BookshelfFragment bookshelfFragment;
    public MessageFragment messageFragment;
    public MineFragment mineFragment;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @BindView(R.id.ivmain_homepage)
    ImageView ivmainHomepage;
    @BindView(R.id.tvmain_homepage)
    TextView tvmainHomepage;
    @BindView(R.id.main_homepage)
    LinearLayout mainHomepage;
    @BindView(R.id.ivmain_bookshelf)
    ImageView ivmainBookshelf;
    @BindView(R.id.tvmain_bookshelf)
    TextView tvmainBookshelf;
    @BindView(R.id.main_bookshelf)
    LinearLayout mainBookshelf;
    @BindView(R.id.ivmain_writer)
    ImageView ivmainWriter;
    @BindView(R.id.main_writer)
    LinearLayout mainWriter;
    @BindView(R.id.ivmain_search)
    ImageView ivmainSearch;
    @BindView(R.id.tvmain_search)
    TextView tvmainSearch;
    @BindView(R.id.main_search)
    RelativeLayout mainSearch;
    @BindView(R.id.ivmain_mine)
    ImageView ivmainMine;
    @BindView(R.id.tvmain_mine)
    TextView tvmainMine;
    @BindView(R.id.main_mine)
    LinearLayout mainMine;
    @BindView(R.id.menu)
    LinearLayout menu;
    @BindView(R.id.main_all)
    LinearLayout mainAll;

    private int id;
    private NoAuthorDialog noAuthorDialog;
    private Intent inten;
    private String code = "0";//0无需更新，1强制更新，2随意更新
    private AuthormessageBean authormessageBean;
    private long sp = 0, su = 0, cc = 0, sp2 = 0;
    private int rec = 0,webtId=0,fl=0;
    private boolean isconceal = false;
    private PhoneBangding phoneBangdingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //获取唤醒参数
        //OpenInstall.getWakeUp(getIntent(), wakeUpAdapter);

        context = this;
        fragmentManager = getSupportFragmentManager();
        //检测版本以及下载更新
        intDownLoad();
        init();
        //是否是推广的书，如果是就跳转到书
        if (getIntent().getBooleanExtra("isfirst", false)) {
            istuiguangBook();
        }

    }

    private void istuiguangBook() {
        OkHttpUtils.get(HttpManager.IP + "/getPromotionInfoByBookID")
                .params("code", StringTool.getChannelName(MainActivity.this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            BookIDBean bookIDBean = gson.fromJson(s, BookIDBean.class);
                            if (bookIDBean.getReturnCode() == 200) {
                                Intent intent = new Intent(MainActivity.this, BookDetailsActivity.class);
                                intent.putExtra("bookId", String.valueOf(bookIDBean.getData().getBookId()));
                                SettingManager.getInstance().saveReadProgress(String.valueOf(bookIDBean.getData().getBookId()), bookIDBean.getData().getChapterOrder(), 0, 0, 1, 0);
                                startActivity(intent);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //wakeUpAdapter = null;
    }

    private void intDownLoad() {
        String verName;
        try {
            verName = getPackageManager().getPackageInfo("com.ljfiction.book", 0).versionName;
            OkHttpUtils.get(HttpManager.IP + "/android/update")
                    .params("userVersion", verName)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("main", s);
                            Gson gson = new Gson();

                            try {
                                VersonBean versonBean = gson.fromJson(s, VersonBean.class);
                                if (versonBean.getReturnCode() == 200) {
                                    code = versonBean.getData().getCode();
                                    if (!"0".equals(code)) {
                                        todownload(versonBean.getData().getVersionDescription(), versonBean.getData().getThisVersion());
                                    }
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);    //将这一行注释掉，阻止activity保存fragment的状态,解决Fragment穿透重叠现像
    }

    private void todownload(String versionDescription, String thisVersion) {

        OkDialog downLoadDialog = new OkDialog(MainActivity.this, versionDescription, thisVersion);
        if ("1".equals(code)) {
            downLoadDialog.hideClose();
        }
        downLoadDialog.setListener(new OkDialog.Listener() {
            @Override
            public void okClick() {
                if (!PermissionUtils.requestPermission(context, 8)) {
                    return;
                }
               /* RxPermissions.getInstance(MainActivity.this)
                        // 申请权限
                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean granted) {
                                if(granted){
                                    //请求成功
                                    showNoticeDialog();

                                }else{
                                    // 请求失败回收当前服务


                                }
                            }
                        });*/

                downLoadDialog.dismiss();
                if ("2".equals(code)) {
                    Intent intent = new Intent(MainActivity.this, DownLoadService.class);
                    intent.putExtra("downloadURL", HttpManager.DowloadIP + "/apk/app.apk");
                    startService(intent);
                } else if ("1".equals(code)) {
                    final NewVersionDialog newVersionDialog = new NewVersionDialog(MainActivity.this);
                    newVersionDialog.show();
                    HttpUtils httpUtils = new HttpUtils();
                    httpUtils.download(HttpManager.DowloadIP + "/apk/app.apk", Environment.getExternalStorageDirectory()
                                    + "/app-lajixs.apk",
                            new RequestCallBack<File>() {

                                @Override
                                public void onSuccess(ResponseInfo<File> responseInfo) {
                                    int checkSelfPermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);

                                    if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                                        ActivityCompat.requestPermissions((Activity) getApplicationContext(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                11);
                                    } else {
                                        Intent intent2 = new Intent(Intent.ACTION_VIEW);
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                            intent2.setAction("android.intent.action.VIEW");
                                            intent2.addCategory("android.intent.category.DEFAULT");
                                            intent2.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                            Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.ljfiction.book.fileprovider", responseInfo.result);
                                            intent2.setDataAndType(contentUri, "application/vnd.android.package-archive");
                                        } else {
                                            intent2.setAction("android.intent.action.VIEW");
                                            intent2.addCategory("android.intent.category.DEFAULT");
                                            intent2.setDataAndType(Uri.fromFile(responseInfo.result), "application/vnd.android.package-archive");
                                            intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        }
                                        getApplicationContext().startActivity(intent2);
                                    }


                                }

                                public void onLoading(long total, long current, boolean isUploading) {
                                    newVersionDialog.setProgressBar((int) (((double) current / (double) total) * 100));
                                }

                                @Override
                                public void onFailure(HttpException error,
                                                      String msg) {
                                }
                            });
                }

            }

            @Override
            public void closeClick() {

            }
        });

    }

    /*
     * tishi
     * */
    private TextView textView;
    private ImageView imageView;
    private View layout;
    private Toast toast;

    @SuppressLint("InflateParams")
    private void showToast() {
        if (toast == null) {
            LayoutInflater inflater = LayoutInflater.from(this);
            layout = inflater.inflate(R.layout.shouhuolajiao, null);
            textView = layout.findViewById(R.id.numshouhuotext);
            imageView = layout.findViewById(R.id.tishiimage);
            if (rec > 0) {
                textView.setText(StringTool.getNum(rec));
                textView.setVisibility(View.VISIBLE);
                imageView.setImageResource(R.mipmap.tishishouhuo);
            } else {
                textView.setVisibility(View.GONE);
                imageView.setImageResource(R.mipmap.tishinoshouhuo);
            }

            toast = new Toast(this);
            toast.setGravity(Gravity.CENTER, 0, -100);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        } else {
            if (rec > 0) {
                textView.setText(StringTool.getNum(rec));
                textView.setVisibility(View.VISIBLE);
                imageView.setImageResource(R.mipmap.tishishouhuo);
            } else {
                textView.setVisibility(View.GONE);
                imageView.setImageResource(R.mipmap.tishinoshouhuo);
            }
            toast.setView(layout);
            toast.show();
        }
    }
    @SuppressLint("CommitTransaction")
    private void init() {
        homeFragment = HomeFragment.newInstance((FistHom) getIntent().getSerializableExtra("firstHome"), getIntent().getBooleanExtra("isfirst", false));
        addFragment(fragmentManager.beginTransaction(), R.id.frameLayout, homeFragment, false);
        initBottomMenu();
    }


    private void initBottomMenu() {
        id = R.id.frameLayout;
        mainHomepage.setOnClickListener(v -> toHome());

        mainBookshelf.setOnClickListener(v -> {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            hideFragments(transaction);
            tvmainBookshelf.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_delet_main));
            ivmainBookshelf.setImageResource(R.drawable.booklet_select);
            if (bookshelfFragment == null) {
                bookshelfFragment = new BookshelfFragment().setMainlistener(mainlistener);
                addFragment(transaction, id, bookshelfFragment, false);
            } else {
                showFragment(transaction, id, bookshelfFragment, false);
            }
        });
        mainWriter.setOnClickListener(v -> {

            if (!UserManageBean.isLogin(MainActivity.this)) {
                return;
            }
            if (!UserManageBean.isAuthor1(MainActivity.this)) {
                if (noAuthorDialog == null) {
                    noAuthorDialog = new NoAuthorDialog(MainActivity.this, new NoAuthorDialog.Listener() {
                        @Override
                        public void isokToauthor() {
                            if (UserManageBean.userBean.getUserPhone().equals("0")) {
                                if (phoneBangdingDialog == null) {
                                    phoneBangdingDialog = new PhoneBangding(context);
                                    phoneBangdingDialog.setListener(new PhoneBangding.Listener() {
                                        @Override
                                        public void giveyanzhengnoLogin() {
                                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                                            startActivity(intent);

                                        }

                                        @Override
                                        public void setok() {
                                            UserManageBean.backgroundRiches(MainActivity.this);
                                        }

                                        @Override
                                        public void clickquhao() {
                                            Intent intent = new Intent(MainActivity.this, SelectquhaoActivity.class);
                                            startActivityForResult(intent, 10);
                                        }
                                    });
                                }
                                phoneBangdingDialog.show();

                                return;
                            }
                            inten = new Intent(MainActivity.this, ApplyAuthorActivity.class);
                            startActivityForResult(inten, 1);
                        }

                        @Override
                        public void seekauthor() {
                            Intent intent = new Intent(MainActivity.this, AuthorxieyiActivity.class);
                            startActivity(intent);
                        }

                        @Override
                        public void deletnoauthor() {

                        }
                    });
                } else {
                    noAuthorDialog.show();
                }


            } else {
                showMoreWindow(v);
            }
        });

        mainSearch.setOnClickListener(v -> {
            if (!UserManageBean.isLogin(context)) {
                return;
            }
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            hideFragments(transaction);
            tvmainSearch.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_delet_main));
            ivmainSearch.setImageResource(R.drawable.messagered);
            if (messageFragment == null) {
                messageFragment = new MessageFragment().setMainlistener(mainlistener);
                addFragment(transaction, id, messageFragment, false);
            } else {
                showFragment(transaction, id, messageFragment, false);
            }
        });
        mainMine.setOnClickListener(v -> {

            FragmentTransaction transaction = fragmentManager.beginTransaction();
            hideFragments(transaction);
            tvmainMine.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_delet_main));
            ivmainMine.setImageResource(R.drawable.mine_select);
            if (mineFragment == null) {
                mineFragment = MineFragment.newInstance();
                addFragment(transaction, id, mineFragment, false);
            } else {
                showFragment(transaction, id, mineFragment, false);
            }
        });
    }


    public void toHome() {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction);
        tvmainHomepage.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_delet_main));
        ivmainHomepage.setImageResource(R.drawable.home_select);
        if (homeFragment == null) {
            homeFragment = HomeFragment.newInstance((FistHom) getIntent().getSerializableExtra("firstHome"), false);
            addFragment(transaction, id, homeFragment, false);

        } else {
            showFragment(transaction, id, homeFragment, false);
            homeFragment.tohotlist();
        }

    }

    public void hideFragments(FragmentTransaction transaction) {
        if (messageFragment != null) {
            messageFragment.onResume();
        }

        hideFragment(transaction, homeFragment);
        hideFragment(transaction, bookshelfFragment);
        hideFragment(transaction, messageFragment);
        //hideFragment(transaction, writerFragment);
        hideFragment(transaction, mineFragment);
        tvmainHomepage.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_main));
        tvmainBookshelf.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_main));
        tvmainSearch.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_main));
        tvmainMine.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.text_main));
        ivmainHomepage.setImageResource(R.drawable.home_none);
        ivmainBookshelf.setImageResource(R.drawable.booklet_none);
        ivmainSearch.setImageResource(R.drawable.messageimage);
        ivmainMine.setImageResource(R.drawable.mine_none);

    }


    //监听返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private HomwriterWindow mMoreWindow;


    private void showMoreWindow(View view) {
        if (mMoreWindow != null) {
            mMoreWindow.showHomwriterWindow(view,100);
            toMessage();
        } else {
            mMoreWindow = new HomwriterWindow(this);
            mMoreWindow.setListener(() -> {
                if (toast != null) {
                    toast.cancel();
                }
            });
            mMoreWindow.setSpuc(sp, su, cc, sp2,webtId,fl);
            mMoreWindow.init();
            mMoreWindow.showHomwriterWindow(view,100);
            toMessage();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        isconceal = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isconceal = true;
        if (toast != null) {
            toast.cancel();
        }
    }

    public Mainlistener mainlistener = new Mainlistener() {
        @Override
        public void tohom() {
            toHome();
        }

        @Override
        public void hidebottom() {
            menu.setVisibility(View.GONE);
        }

        @Override
        public void showbottom() {
            menu.setVisibility(View.VISIBLE);
        }

        @Override
        public void showmessage(int num) {
            if (num > 0) {
                messageNumcard.setVisibility(View.VISIBLE);
                messageNumtext.setText(num);
            } else {
                messageNumcard.setVisibility(View.GONE);
            }
        }

    };


    //退出方法
    private long time = 0;

    private void exit() {
        //如果在两秒大于2秒
        if (System.currentTimeMillis() - time > 2000) {

            //获得当前的时间

            time = System.currentTimeMillis();

            showToast("再点击一次退出应用程序");

        } else {
            //点击在两秒以内

            removeALLActivity();//执行移除所以Activity方法

        }

    }

    class ViewHolder {
        @BindView(R.id.isok_toauthor)
        SuperButton isokToauthor;
        @BindView(R.id.seekauthor)
        TextView seekauthor;
        @BindView(R.id.deletnoauthor)
        ImageView deletnoauthor;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    private void toMessage() {
        //获取是否有消息
        OkHttpUtils.post(HttpManager.IP + "/getAuthorMessageStatus")

                .params("spid", SettingManager.getInstance().getAuthorMessage("sp"))
                .params("suid", SettingManager.getInstance().getAuthorMessage("su"))
                .params("spid2", SettingManager.getInstance().getAuthorMessage("sp2"))
                .params("webtId", SettingManager.getInstance().getAuthorMessage("webtId"))
                .params("menuId","2")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            authormessageBean = gson.fromJson(s, AuthormessageBean.class);
                            if (authormessageBean.getReturnCode() == 200) {
                                sp = authormessageBean.getData().getSp();
                                su = authormessageBean.getData().getSu();
                                cc = authormessageBean.getData().getCc().size()+authormessageBean.getData().getPp().size()>0?1:0;
                                sp2 = authormessageBean.getData().getSp2();
                                rec = authormessageBean.getData().getRec();
                                webtId=authormessageBean.getData().getWebannouncementCount();
                                fl=authormessageBean.getData().getWelfare();
                                if (mMoreWindow != null && mMoreWindow.isShowing()) {
                                    mMoreWindow.setSpuc(sp, su, cc, sp2,webtId,fl);
                                    mMoreWindow.setImageDian();
                                    if (!isconceal) {
                                        showToast();
                                    }

                                }
                            } else if (authormessageBean.getReturnCode() == 400) {
                                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                                startActivity(intent);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            //noAuthorPopuWindow.dismiss();
            noAuthorDialog.close();
            inten = new Intent(MainActivity.this, CreatBookActivity.class);
            startActivity(inten);
        } else if (requestCode == 10 && resultCode == 10) {
            if (phoneBangdingDialog != null) {
                phoneBangdingDialog.setQuhao(data.getStringExtra("countryNumber"));
            }
        }
        /*if (resultCode == 10) {
            PreferencesTool.saveLoginInfo(this, data.getStringExtra("phoneId"), data.getStringExtra("password"));
            PreferencesTool.saveValue(this, "isChecked", "1");
            inten = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(inten);
        }*/
    }
}
